package com.hliu.core.dao.hibernate4;

import com.hliu.core.dao.IBaseHibernateDao;
import org.hibernate.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

/**
 * author: 6
 * date: 13-4-9
 */
public abstract class BaseHibernateDao<T extends Serializable, PK extends Serializable> implements IBaseHibernateDao<T, PK> {

	private Class<T> clazz;

	protected BaseHibernateDao(Class<T> clazz) {
		this.clazz = clazz;
	}

	protected BaseHibernateDao() {
		this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;

	public Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	@SuppressWarnings("unchecked")
	public T get(PK id) {
		return (T) getCurrentSession().get(clazz, id);
	}

	@Override
	public T load(PK id) {
		return (T) getCurrentSession().load(clazz, id);
	}

	@Override
	public void save(T t) {
		getCurrentSession().save(clazz.getName(), t);
	}

	@Override
	public void update(T t) {
		getCurrentSession().update(clazz.getName(), t);
	}

	@Override
	public List<T> list() {
		return createCriteria().list();
	}

	@Override
	public void saveOrUpdate(T t) {
		getCurrentSession().saveOrUpdate(clazz.getName(), t);
	}

	@Override
	public void delete(T t) {
		getCurrentSession().delete(t);
	}

	@Override
	public void del(PK id) {
		delete(this.get(id));
	}

	@Override
	public SQLQuery createSQLQuery(String queryString) {
		return getCurrentSession().createSQLQuery(queryString);
	}

	@Override
	public Criteria createCriteria() {
		return getCurrentSession().createCriteria(clazz);
	}

	@Override
	public Query createQuery(String queryString) {
		return getCurrentSession().createQuery(queryString);
	}
}
